using Microsoft.AspNetCore.Mvc;
using User.Service;
using hao_Dto.User;
using hao_Common.Response.Extensions;

namespace hao_User.Api.Controllers
{
    /// <summary>
    /// 内部服务调用控制器
    /// 专门用于微服务间的内部通信，不需要用户认证
    /// </summary>
    [ApiController]
    [Route("api/internal/user")]
    public class InternalController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ILogger<InternalController> _logger;

        public InternalController(
            IUserService userService,
            ILogger<InternalController> logger)
        {
            _userService = userService;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户详情（内部服务调用）
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户详情</returns>
        /// <response code="200">获取成功</response>
        /// <response code="404">用户不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(UserDto), 200)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetUserInternal(Guid id)
        {
            try
            {
                var user = await _userService.GetUserByIdAsync(id);
                return user == null 
                    ? this.NotFoundResult("用户不存在") 
                    : this.SuccessResult(user, "获取用户信息成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务获取用户详情失败，ID: {UserId}", id);
                return this.ServerErrorResult("获取用户信息失败");
            }
        }

        /// <summary>
        /// 批量获取用户详情（内部服务调用）
        /// </summary>
        /// <param name="ids">用户ID列表</param>
        /// <returns>用户详情列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("batch")]
        [ProducesResponseType(typeof(List<UserDto>), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetUsersBatch([FromBody] List<Guid> ids)
        {
            try
            {
                var users = new List<UserDto>();
                foreach (var id in ids)
                {
                    var user = await _userService.GetUserByIdAsync(id);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }
                return this.SuccessResult(users, "批量获取用户详情成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务批量获取用户详情失败，IDs: {UserIds}", string.Join(",", ids));
                return this.ServerErrorResult("批量获取用户详情失败");
            }
        }

        /// <summary>
        /// 验证用户是否存在且可用（内部服务调用）
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>验证结果</returns>
        /// <response code="200">验证成功</response>
        /// <response code="404">用户不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}/validate")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> ValidateUser(Guid id)
        {
            try
            {
                var user = await _userService.GetUserByIdAsync(id);
                if (user == null)
                {
                    return this.NotFoundResult("用户不存在或已被禁用");
                }

                return this.SuccessResult(new 
                { 
                    id = user.Id,
                    userName = user.UserName,
                    email = user.Email,
                    phone = user.Phone,
                    isActive = true
                }, "用户验证成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务验证用户失败，ID: {UserId}", id);
                return this.ServerErrorResult("验证用户失败");
            }
        }

        /// <summary>
        /// 健康检查（内部服务）
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return this.SuccessResult(new { status = "healthy", service = "user-internal", timestamp = DateTime.UtcNow });
        }
    }
}